package managedbean.SLC;

import java.util.ArrayList;
import java.util.Collection;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import merlion.common.entity.SecurityRole;
import merlion.common.entity.Staff;
import merlion.common.session.stateless.SystemUserSessionBeanLocal;
import merlion.common.util.exception.NotExistException;
import merlion.crm.slcm.entity.Address;
import merlion.crm.slcm.entity.ContactRecord;
import merlion.crm.slcm.entity.Customer;
import merlion.crm.slcm.entity.MemberDiscountGroup;
import merlion.crm.slcm.entity.SalesLead;
import merlion.crm.slcm.session.SLCSessionBeanLocal;
import merlion.crm.sopm.entity.RequestForQuotation;
import merlion.crm.sopm.entity.SalesInquiry;
import merlion.crm.sopm.entity.SalesQuotation;
import merlion.crm.sopm.session.SOPSessionBeanLocal;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Kenn
 */
@ManagedBean(name = "customerManagerBean")
@ViewScoped
public class CustomerManagerBean {

    @EJB
    private SLCSessionBeanLocal sLCSessionBean;
    @EJB
    private SystemUserSessionBeanLocal suBean;
    @EJB
    private SOPSessionBeanLocal sopBean;
    private SalesLead salesLead;
    private Customer customer;
    private ContactRecord contactRecord;
    private ContactRecord contactRecordBackup;
    private Address shippingAddress;
    private Address shippingAddressBackup;
    private Collection<Customer> customers;
    private Staff loginUser;
    private Staff newCE;
    private Collection<MemberDiscountGroup> mdgs;
    private MemberDiscountGroup mdg;

    //----------------------------------------------------------------------
    //                  CustomerManagerBean Constructor
    //----------------------------------------------------------------------
    public CustomerManagerBean() {
        salesLead = new SalesLead();
        customer = new Customer();
        contactRecord = new ContactRecord();
        shippingAddress = new Address();
        customers = new ArrayList<Customer>();
        loginUser = new Staff();
        mdg = new MemberDiscountGroup();
    }

    @PostConstruct
    public void init() {
        customer.setClientId(sLCSessionBean.generateClientID());
        loginUser = (Staff) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("app.user.name");
        // TODO: need to use id to get the staff (done)
        loginUser = suBean.getStaff(loginUser.getId());
        customer.setCustomerExecutive(loginUser);
        // Set credit discount and member discount
        mdg = sLCSessionBean.getMemberDiscountGroupByLimitAccSpendingForDs().get(0);

        //Process view/update request
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            String param = context.getExternalContext().getRequestParameterMap().get("id");
            String urlPath = context.getExternalContext().getRequestContextPath();

            if (param != null) {
                if (context.getExternalContext().getRequestServletPath().contains("Convert")) {
                    Long id = Long.parseLong(param);
                    convertSalesLead(id);
                } else {
                    Long id = Long.parseLong(param);
                    setCustomer(sLCSessionBean.getCustomerById(id));
                    setMdg(customer.getMemberDiscountGroup());
                }
            }
        } catch (NotExistException ex) {
        }
    }

    //--------------------------------------------------------------------------
    //              Customer Manager Bean Form Methods
    //--------------------------------------------------------------------------
    public void addContactRecord() {

        //Validate contact record
        RequestContext context = RequestContext.getCurrentInstance();
        boolean valid = true;

        // Contact Name: Required, Alphabetic
        if (!isNotEmpty(contactRecord.getName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Name", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(contactRecord.getName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Name", "can only contain alphabetical characters."));
            valid = false;
        }

        // Contact Designation: Required, Alphabetic
        if (!isNotEmpty(contactRecord.getJobTitle())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Designation", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(contactRecord.getJobTitle())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Designation", "can only contain alphabetical characters."));
            valid = false;
        }

        // Contact Phone: Required
        if (!isNotEmpty(contactRecord.getPhone())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Phone", "cannot be empty."));
            valid = false;
        }

        // Contact Email: Required, is valid email
        if (!isNotEmpty(contactRecord.getEmail())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "E-mail", "cannot be empty."));
            valid = false;
        }
        if (!isValidEmailAddress(contactRecord.getEmail())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "E-mail", "is not valid."));
            valid = false;
        }
        context.addCallbackParam("valid", valid);

        if (valid) {
            customer.getContactRecords().add(contactRecord);
            //Reset Contact Record
            contactRecord = new ContactRecord();
        }
    }

    public void updateContactRecordBackup(ActionEvent event) {

        contactRecord = (ContactRecord) event.getComponent().getAttributes().get("selectedContactRecord");

        contactRecordBackup = new ContactRecord();
        contactRecordBackup.setEmail(contactRecord.getEmail());
        contactRecordBackup.setId(contactRecord.getId());
        contactRecordBackup.setJobTitle(contactRecord.getJobTitle());
        contactRecordBackup.setName(contactRecord.getName());
        contactRecordBackup.setPhone(contactRecord.getPhone());
        contactRecordBackup.setTimeCreated(contactRecord.getTimeCreated());
    }

    public void updateContactRecord() {
        //Validate contact record
        RequestContext context = RequestContext.getCurrentInstance();
        boolean valid = true;

        // Contact Name: Required, Alphabetic
        if (!isNotEmpty(contactRecord.getName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Name", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(contactRecord.getName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Name", "can only contain alphabetical characters."));
            valid = false;
        }

        // Contact Designation: Required, Alphabetic
        if (!isNotEmpty(contactRecord.getJobTitle())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Designation", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(contactRecord.getJobTitle())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Designation", "can only contain alphabetical characters."));
            valid = false;
        }

        // Contact Phone: Required
        if (!isNotEmpty(contactRecord.getPhone())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Phone", "cannot be empty."));
            valid = false;
        }

        // Contact Email: Required, is valid email
        if (!isNotEmpty(contactRecord.getEmail())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "E-mail", "cannot be empty."));
            valid = false;
        }
        if (!isValidEmailAddress(contactRecord.getEmail())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "E-mail", "is not valid."));
            valid = false;
        }
        context.addCallbackParam("valid", valid);

        if (valid) {
            for (ContactRecord cr : customer.getContactRecords()) {
                if (cr.equals(contactRecord)) {
                    cr = contactRecord;
                }
            }
            //Reset contact record
            contactRecord = new ContactRecord();
        }
    }

    public void resetContactRecord() {

        contactRecord.setName(contactRecordBackup.getName());
        contactRecord.setEmail(contactRecordBackup.getEmail());
        contactRecord.setJobTitle(contactRecordBackup.getJobTitle());
        contactRecord.setPhone(contactRecordBackup.getPhone());
        contactRecord.setTimeCreated(contactRecordBackup.getTimeCreated());

        contactRecord = new ContactRecord();
    }

    public void deleteContactRecord() {
        customer.getContactRecords().remove(contactRecord);

        //Reset contact record
        contactRecord = new ContactRecord();
    }

    public void addShippingAddress() {
        RequestContext context = RequestContext.getCurrentInstance();
        boolean valid = true;

        // Address Line 1: Alphanumeric, Required
        if (!isNotEmpty(shippingAddress.getAddressLine1())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Line 1", "cannot be empty."));
            valid = false;
        }

        // Address Line 2: Alphanumeric, Required
        if (!isNotEmpty(shippingAddress.getAddressLine2())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Line 2", "cannot be empty."));
            valid = false;
        }

        // Zipcode: Numeric, Required
        if (!isNotEmpty(shippingAddress.getZipCode())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Zip Code", "cannot be empty."));
            valid = false;
        }
        if (!isNumeric(shippingAddress.getZipCode())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Zip Code", "can only contain numeric characters."));
            valid = false;
        }

        // City: Alphabetic, Required
        if (!isNotEmpty(shippingAddress.getCity())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address City", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(shippingAddress.getCity())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address City", "can only contain alphabetical characters."));
            valid = false;
        }

        // State: Alphabetic, Required
        if (!isNotEmpty(shippingAddress.getStateName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address State", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(shippingAddress.getStateName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address State", "can only contain alphabetical characters."));
            valid = false;
        }

        //Country: Alphabetic, Required
        if (!isNotEmpty(shippingAddress.getCountry())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Country", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(shippingAddress.getCountry())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Country", "can only contain alphabetical characters."));
            valid = false;
        }

        context.addCallbackParam("valid", valid);

        if (valid) {
            customer.getShippingAddress().add(shippingAddress);

            //Reset shipping address
            shippingAddress = new Address();
        }
    }

    public void updateShippingAddress() {

        RequestContext context = RequestContext.getCurrentInstance();
        boolean valid = true;

        // Address Line 1: Alphanumeric, Required
        if (!isNotEmpty(shippingAddress.getAddressLine1())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Line 1", "cannot be empty."));
            valid = false;
        }

        // Address Line 2: Alphanumeric, Required
        if (!isNotEmpty(shippingAddress.getAddressLine2())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Line 2", "cannot be empty."));
            valid = false;
        }

        // Zipcode: Numeric, Required
        if (!isNotEmpty(shippingAddress.getZipCode())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Zip Code", "cannot be empty."));
            valid = false;
        }
        if (!isNumeric(shippingAddress.getZipCode())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Zip Code", "can only contain numeric characters."));
            valid = false;
        }

        // City: Alphabetic, Required
        if (!isNotEmpty(shippingAddress.getCity())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address City", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(shippingAddress.getCity())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address City", "can only contain alphabetical characters."));
            valid = false;
        }

        // State: Alphabetic, Required
        if (!isNotEmpty(shippingAddress.getStateName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address State", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(shippingAddress.getStateName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address State", "can only contain alphabetical characters."));
            valid = false;
        }

        //Country: Alphabetic, Required
        if (!isNotEmpty(shippingAddress.getCountry())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Country", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(shippingAddress.getCountry())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address Country", "can only contain alphabetical characters."));
            valid = false;
        }

        context.addCallbackParam("valid", valid);

        if (valid) {
            for (Address sa : customer.getShippingAddress()) {
                if (sa.equals(shippingAddress)) {
                    sa = shippingAddress;
                }
            }
            //Reset shipping address
            shippingAddress = new Address();
        }
    }

    public void updateShippingAddressBackup(ActionEvent event) {

        shippingAddress = (Address) event.getComponent().getAttributes().get("selectedShippingAddress");

        shippingAddressBackup = new Address();
        shippingAddressBackup.setAddressLine1(shippingAddress.getAddressLine1());
        shippingAddressBackup.setAddressLine2(shippingAddress.getAddressLine2());
        shippingAddressBackup.setAddressType(shippingAddress.getAddressType());
        shippingAddressBackup.setCity(shippingAddress.getCity());
        shippingAddressBackup.setCountry(shippingAddress.getCountry());
        shippingAddressBackup.setStateName(shippingAddress.getStateName());
        shippingAddressBackup.setTimeCreated(shippingAddress.getTimeCreated());
        shippingAddressBackup.setZipCode(shippingAddress.getZipCode());
    }

    public void deleteShippingAddress() {
        customer.getShippingAddress().remove(shippingAddress);

        //Reset shipping address
        shippingAddress = new Address();
    }

    public void resetShippingAddress() {

        shippingAddress.setAddressLine1(shippingAddressBackup.getAddressLine1());
        shippingAddress.setAddressLine2(shippingAddressBackup.getAddressLine2());
        shippingAddress.setAddressType(shippingAddressBackup.getAddressType());
        shippingAddress.setCity(shippingAddressBackup.getCity());
        shippingAddress.setCountry(shippingAddressBackup.getCountry());
        shippingAddress.setStateName(shippingAddressBackup.getStateName());
        shippingAddress.setTimeCreated(shippingAddressBackup.getTimeCreated());
        shippingAddress.setZipCode(shippingAddressBackup.getZipCode());

        shippingAddress = new Address();
    }

    public String viewAllCustomer() {
        return "/SLC/viewAllCustomer?faces-redirect=true";
    }

    public String createCustomer() {

        // Get credit group and member discount group
        mdg = sLCSessionBean.getMemberDiscountGroupById(mdg.getId());

        if (validate(customer, mdg)) {

            // Credit account, credit group and customer
            customer.setCreditAccount(null);

            // Member Discount group, customer
            customer.setMemberDiscountGroup(mdg);
            mdg.getCustomers().add(customer);

            // Call EJB to persist object.
            customer = sLCSessionBean.createCustomer(customer);

            return "confirm";
        }
        return null;
    }

    public String viewCustomer(Long id) {
        return "viewAllCustomerView?id=" + id + "&faces-redirect=true";
    }

    public String updateCustomer(Long id) {
        return "viewAllCustomerUpdate?id=" + id + "&faces-redirect=true";
    }

    public String saveUpdatedCustomer() {

        if (validate(customer, mdg)) {
            
            mdg = sLCSessionBean.getMemberDiscountGroupById(mdg.getId());

            
            // Member Discount group, customer
            // Remove customer from old member discount group
            
            // Add customer to new member discount group
            customer.setMemberDiscountGroup(mdg);
            
            // Call EJB to persist object.
            customer = sLCSessionBean.createCustomer(customer);

            return "confirm";
        }

        return null;
    }

    public void updateCustomerExecutive() {

        Staff currCE = customer.getCustomerExecutive();
        if (!newCE.equals(currCE)) {
            newCE.getSalesLeads().add(customer);
            currCE.getSalesLeads().remove(customer);
            customer.setCustomerExecutive(newCE);
        }
    }

    public boolean renderUpdate(Customer customer) {
        boolean render = false;
        if (customer.getCustomerExecutive().equals(loginUser)) {
            render = true;
        }
        for (SecurityRole sr : loginUser.getSecurityRoles()) {
            if (sr.getRoleName().equals("SalesManager") || sr.getRoleName().equals("SalesVP")) {
                render = true;
            }
        }
        return render;
    }

    //--------------------------------------------------------------------------
    //             Customer Manager Bean DataTable Methods
    //--------------------------------------------------------------------------
    public Collection<Customer> getAllCustomer() {
        setCustomers(sLCSessionBean.getAllCustomer());
        return customers;
    }

    public Collection<MemberDiscountGroup> getAllMdgs() {
        setMdgs(sLCSessionBean.getAllMemberDiscountGroup());
        return mdgs;
    }

    private void convertSalesLead(Long id) {

        try {
            salesLead = sLCSessionBean.getSalesLeadById(id);
            customer.setClientId(salesLead.getClientId());
            customer.setCompanyName(salesLead.getCompanyName());
            customer.setCategory(salesLead.getCategory());
            customer.setIndustry(salesLead.getIndustry());
            customer.setContactRecords(salesLead.getContactRecords());
            customer.setShippingAddress(salesLead.getShippingAddress());
            customer.setCustomerExecutive(salesLead.getCustomerExecutive());
            customer.setSalesInquiries(salesLead.getSalesInquiries());
            customer.setSalesQuotations(salesLead.getSalesQuotations());
            customer.setRequestForQuotations(salesLead.getRequestForQuotations());
        } catch (Exception e) {
            System.out.println("Convert Sales Lead Failed: " + e.getMessage());
        }
    }

    public String convert() {

        // Set and member discount group
        mdg = sLCSessionBean.getMemberDiscountGroupById(mdg.getId());

        if (validate(customer, mdg)) {
            customer = sLCSessionBean.createCustomer(customer);

            customer.setCreditAccount(null);
            customer.setMemberDiscountGroup(mdg);

            // Set customer executive
            for (Staff sa : suBean.getAllStaff()) {
                sa.getSalesLeads().remove(salesLead);
            }
            customer.getCustomerExecutive().getSalesLeads().add(customer);

            // Set existing sales document to customer
            for (SalesQuotation sq : sopBean.getAllSalesQuotation()) {
                if (sq.getClient().equals(salesLead)) {
                    sq.setClient(customer);
                    sopBean.saveSalesQuotation(sq);
                }
            }
            for (SalesInquiry salesInquiry : sopBean.getAllSalesInquirys()) {
                if (salesInquiry.getSalesLead().equals(salesLead)) {
                    salesInquiry.setSalesLead(customer);
                    sopBean.saveSalesInquiry(salesInquiry);
                }
            }
            for (RequestForQuotation rfq : sopBean.getAllRequestForQuotation()) {
                if (rfq.getSalesLead().equals(salesLead)) {
                    rfq.setSalesLead(customer);
                    sopBean.saveRequestForQuotation(rfq);
                }
            }

            sLCSessionBean.updateCustomer(customer);

            // Unlink all relations and Remove sales lead
            salesLead.setRequestForQuotations(null);
            salesLead.setSalesInquiries(null);
            salesLead.setSalesQuotations(null);
            salesLead.setCustomerExecutive(null);
            salesLead.setContactRecords(null);
            salesLead.setShippingAddress(null);
            sLCSessionBean.removeSalesLead(salesLead);

            return "confirm";
        }

        return null;
    }
    //----------------------------------------------------------------------
    //            CustomerManagerBean Accessor and Mutator Methods
    //----------------------------------------------------------------------

    public ContactRecord getContactRecord() {
        return contactRecord;
    }

    public void setContactRecord(ContactRecord contactRecord) {
        this.contactRecord = contactRecord;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Collection<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(Collection<Customer> customers) {
        this.customers = customers;
    }

    public Staff getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Staff loginUser) {
        this.loginUser = loginUser;
    }

    public Staff getNewCE() {
        return newCE;
    }

    public void setNewCE(Staff newCE) {
        this.newCE = newCE;
    }

    public SalesLead getSalesLead() {
        return salesLead;
    }

    public void setSalesLead(SalesLead salesLead) {
        this.salesLead = salesLead;
    }

    public Address getShippingAddress() {
        return shippingAddress;
    }

    public void setShippingAddress(Address shippingAddress) {
        this.shippingAddress = shippingAddress;
    }

    public Collection<MemberDiscountGroup> getMdgs() {
        return mdgs;
    }

    public void setMdgs(Collection<MemberDiscountGroup> mdgs) {
        this.mdgs = mdgs;
    }

    public MemberDiscountGroup getMdg() {
        return mdg;
    }

    public void setMdg(MemberDiscountGroup mdg) {
        this.mdg = mdg;
    }

    //-------------------------------------------------------------------------
    //              CustomerManager Bean Customer Validator
    //-------------------------------------------------------------------------
    private boolean isValidEmailAddress(String email) {
        if (email.matches("[\\w\\.-]*[a-zA-Z0-9_]@[\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]")) {
            return true;
        }
        return false;
    }

    private boolean isAlphabetic(String str) {
        if (str.matches("[a-zA-Z\\s]*")) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isAlphanumeric(String str) {

        if (str.matches("[a-zA-z0-9\\s]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNumeric(String str) {
        if (str.matches("[0-9]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNotEmpty(String str) {
        if (str == null) {
            return false;
        }
        if (str.equals("")) {
            return false;
        }
        return true;
    }

    private boolean validate(Customer customer, MemberDiscountGroup mdg) {

        boolean valid = true;

        // Company Name: Required, Alphanumeric
        if (!isNotEmpty(customer.getCompanyName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Company Name", "cannot be empty."));
            valid = false;
        }
        if (!isAlphanumeric(customer.getCompanyName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Company Name", "can only contain alphanumeric characters."));
            valid = false;
        }

        // Category: Required
        if (!isNotEmpty(customer.getCategory())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Category", "cannot be empty."));
            valid = false;
        }

        // Contact Record
        // Check has at least one contact record
        if (customer.getContactRecords().isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Contact Record List", "must contain at least one contact record"));
            valid = false;
        }

        //Shipping Address
        //Check at least one shipping address
        if (customer.getShippingAddress().isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Shipping Address List", "must contain at least one shipping address"));
            valid = false;
        }

        // Billing Address
        // Address Line 1: Alphanumeric, Required
        if (!isNotEmpty(customer.getBillingAddress().getAddressLine1())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Line 1", "cannot be empty."));
            valid = false;
        }
        if (!isAlphanumeric(customer.getBillingAddress().getAddressLine1())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Line 1", "can only contain alphanumeric characters."));
            valid = false;
        }

        // Address Line 2: Alphanumeric, Required
        if (!isNotEmpty(customer.getBillingAddress().getAddressLine2())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Line 2", "cannot be empty."));
            valid = false;
        }
        if (!isAlphanumeric(customer.getBillingAddress().getAddressLine2())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Line 2", "can only contain alphanumeric characters."));
            valid = false;
        }

        // Zipcode: Numeric, Required
        if (!isNotEmpty(customer.getBillingAddress().getZipCode())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Zip Code", "cannot be empty."));
            valid = false;
        }
        if (!isNumeric(customer.getBillingAddress().getZipCode())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Zip Code", "can only contain numeric characters."));
            valid = false;
        }

        // City: Alphabetic, Required
        if (!isNotEmpty(customer.getBillingAddress().getCity())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address City", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(customer.getBillingAddress().getCity())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address City", "can only contain alphabetical characters."));
            valid = false;
        }

        // State: Alphabetic, Required
        if (!isNotEmpty(customer.getBillingAddress().getStateName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address State", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(customer.getBillingAddress().getStateName())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address State", "can only contain alphabetical characters."));
            valid = false;
        }

        //Country: Alphabetic, Required
        if (!isNotEmpty(customer.getBillingAddress().getCountry())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Country", "cannot be empty."));
            valid = false;
        }
        if (!isAlphabetic(customer.getBillingAddress().getCountry())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Billing Address Country", "can only contain alphabetical characters."));
            valid = false;
        }

        // Member discount group
        System.out.println("Customer Purchase " + customer.getAccumulatedPurchases() + ", " + mdg.getAccSpendingForDs() + " " + mdg.getAccSpendingForWs());
        if (customer.getCategory() != null && mdg != null) {
            if (customer.getCategory().equals("WholeSale")) {
                if (mdg.getId() != -1) {
                    // Set credit group and member discount group
                    mdg = sLCSessionBean.getMemberDiscountGroupById(mdg.getId());
                    if (customer.getAccumulatedPurchases() < mdg.getAccSpendingForWs()) {
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount Group", "Customer has not reached the accumulated amount for selected group."));
                        valid = false;
                    }
                } else {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount Group", "Please select a member discount group."));
                    valid = false;
                }

            } else {
                if (mdg.getId() != -1) {
                    mdg = sLCSessionBean.getMemberDiscountGroupById(mdg.getId());
                    if (customer.getAccumulatedPurchases() < mdg.getAccSpendingForDs()) {
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount Group", "Customer has not reached the accumulated amount for selected group."));
                        valid = false;
                    }
                } else {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount Group", "Please select a member discount group."));
                    valid = false;
                }
            }
        }


        return valid;
    }
}